<?php

/**
 * класс для работы с таблицей категорий
 *
 * @author kingop
 */
class DatabaseObject_Categories extends DatabaseObject {

    public $child = '';

    public function __construct($db) {
        parent::__construct($db, 'categories', 'id');

        // далее перечислены все поля таблицы

        $this->add('name');
        $this->add('alias');
        $this->add('title');
        $this->add('descr');
        $this->add('keywords');
        $this->add('content');
        $this->add('parent_id');
        $this->add('count');
        $this->add('level');
    }

    public static function GetCategories($db, $options = array()) {
        // инициализируем настройки
        $defaults = array(
            'where' => '',
            'offset' => 0,
            'limit' => 0,
            'order' => 'p.id'
        );

        foreach ($defaults as $k => $v) {
            $options[$k] = array_key_exists($k, $options) ? $options[$k] : $v;
        }

        $select = self::_GetBaseQuery($db, $options);

        // поля для выборки
        $select->from(null, 'p.*');

        // зададим настройки
        if ($options['limit'] > 0)
            $select->limit($options['limit'], $options['offset']);
        if ($options['where'])
            $select->where($options['where']);

        $select->order($options['order']);

        // получим данные из базы
        $data = $db->fetchAll($select);

        // сделаем из полученных записей объекты класса
        $cats = self::BuildMultiple($db, __CLASS__, $data);
        $cat_ids = array_keys($cats);

        if (count($cat_ids) == 0)
            return array();

        return $cats;
    }

    private static function _GetBaseQuery($db, $options) {
        // инициализация настроек
        $defaults = array();

        foreach ($defaults as $k => $v) {
            $options[$k] = array_key_exists($k, $options) ? $options[$k] : $v;
        }
        // создание запроса на получение
        $select = $db->select();
        $select->from(array('p' => 'categories'), array());

        return $select;
    }

    public static function GetCount($db) {
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, 'count(*)');

        return $db->fetchOne($select);
    }

    public static function SetProductsCount($db, $id, $count) {
        $cat = new DatabaseObject_Categories($db);
        $cat->load($id);
       
        if ($count != 1)
            $cat->count = $cat->count - 1;
        else
            $cat->count = $cat->count + 1;
        $cat->save();
        return true;
        //return $db->fetchOne($select);
    }

    public static function GetCatsParent($db, $catId) {
        $cats = new DatabaseObject_Categories($db);
        $cats->load($catId);
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, '*');
        $select->where('parent_id  = ?', $cats->parent_id);
        $data = $db->fetchAll($select);
        foreach ($cats as $key => $value) {

            $value->child = DatabaseObject_Categories::GetChild($db, $value->getId(), true);
        }

        $cats = self::BuildMultiple($db, __CLASS__, $data);

        return $cats;
    }
    
    public function getProductsCount() {
        return DatabaseObject_Products::GetUserProductCount($this->getDb(), false, $this->getId(), false);
    }

    // получение всех категорий
    public static function GetAllParent($db, $options = array()) {
        $defaults = array(
            'where' => '',
            'offset' => 0,
            'limit' => 0,
            'order' => 'p.name'
        );

        foreach ($defaults as $k => $v) {
            $options[$k] = array_key_exists($k, $options) ? $options[$k] : $v;
        }
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, '*');
        $select->where('parent_id  = 0');
        // зададим настройки
        if ($options['limit'] > 0)
            $select->limit($options['limit'], $options['offset']);
        if ($options['where'])
            $select->where($options['where']);

        $select->order($options['order']);
        $data = $db->fetchAll($select);


        $cats = self::BuildMultiple($db, __CLASS__, $data);
        foreach ($cats as $key => $value) {
            $value->count = DatabaseObject_Products::GetUserProductCount($db, false, $value->getId());
            $value->child = DatabaseObject_Categories::GetChildOne($db, $value->getId());
             foreach ($value->child as $child) {
            $child->count = DatabaseObject_Products::GetUserProductCount($db, false, $child->getId());
          // $child->child = DatabaseObject_Categories::GetChildOne($db, $child->getId());
        }
        }
        return $cats;
    }

    //получение дочерних категорий
    public static function GetChild($db, $catId = 0, $flag = false) {
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, '*');
        $select->where('parent_id  = ?', $catId);
        $data = $db->fetchAll($select);
        if (count($data) == 0 && $catId != 0 && $flag) {
            $cats22 = DatabaseObject_Categories::GetCatsParent($db, $catId);
            return $cats22;
        }

        $cats = self::BuildMultiple($db, __CLASS__, $data);
        if (!$flag)
            foreach ($cats as $key => $value) {
                $value->count = DatabaseObject_Products::GetUserProductCount($db, false, $value->getId());
                $value->child = DatabaseObject_Categories::GetChild($db, $value->getId());
                  foreach ($value->child as $child) {
                       $child->count = DatabaseObject_Products::GetUserProductCount($db, false, $child->getId());
            }
            }
        return $cats;
    }

    public static function GetCatsMenu($db, $catId = 0, $flag = false) {
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, '*');
        $select->where('parent_id  = ?', $catId);
        $data = $db->fetchAll($select);
        if (count($data) == 0 && $catId != 0 && $flag) {
            $cats22 = DatabaseObject_Categories::GetCatsParent($db, $catId);
            return $cats22;
        }

        $cats = self::BuildMultiple($db, __CLASS__, $data);
        if (!$flag)
            foreach ($cats as $key => $value) {

                $value->child = DatabaseObject_Categories::GetChild($db, $value->getId());
            }
        return $cats;
    }

    public static function GetChildId($db, $catId, $lvl=0) {
        static $lvl=0;
        static $k;
        $one = array();
        
        $lvl++;
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, 'id');
        $select->where('parent_id  = ?', $catId);
       
        $data = $db->fetchAll($select);
        $cats =  $data;
        foreach ($cats as $key => $value) {
             $one[]= $value['id'];
             DatabaseObject_Categories::GetChildId($db, $value['id'],$lvl);
            $lvl--;
        }
        $lvl--;
          $one[]= $catId;
        return $one;
    }
     

    // создание крошек категорий
    public static function GetParentKroshki($db, $catId) {
        global $kk;
        $cats1 = new DatabaseObject_Categories($db);
        $cats1->load($catId);

        $kk[] = $cats1;
        if ($cats1->parent_id != 0) {
            DatabaseObject_Categories::GetParentKroshki($db, $cats1->parent_id);
        }
        return $kk;
    }

    //получение категорий одного уровня
    public static function GetChildOne($db, $catId) {

        $select = self::_GetBaseQuery($db, array());
        $select->from(null, '*');
        $select->where('parent_id  = ?', $catId);
        $data = $db->fetchAll($select);

        $cats = self::BuildMultiple($db, __CLASS__, $data);

        return $cats;
    }

    public static function GetParentId($db, $catId) {
        $cats1 = new DatabaseObject_Categories($db);
        $cats1->load($catId);

        if ($cats1->parent_id != 0) {
            $catsparent = new DatabaseObject_Categories($db);
            $catsparent->load($cats1->parent_id);

            $select = self::_GetBaseQuery($db, array());
            $select->from(null, '*');
            $select->where('parent_id  = ?', $catsparent->parent_id);
            $data = $db->fetchAll($select);
            $cats = self::BuildMultiple($db, __CLASS__, $data);
            foreach ($cats as $key => $value) {

                $value->child = DatabaseObject_Categories::GetChildOne($db, $value->getId());
            }
            return $cats;
        } else {
            $select = self::_GetBaseQuery($db, array());
            $select->from(null, '*');
            $select->where('parent_id  = ?', $catId);
            $data = $db->fetchAll($select);
            $cats = self::BuildMultiple($db, __CLASS__, $data);
            foreach ($cats as $key => $value) {

                $value->child = DatabaseObject_Categories::GetChildOne($db, $value->getId());
            }
            return $cats;
        }
    }

    // получение id категории по alias
    public static function GetAliasCat($db, $cat, $cat1='',$cat2='',$cat3='') {
        $query =("SELECT id FROM `categories` WHERE alias = '$cat'");
        $category = $db->fetchOne($query);
     /*   if ($cat1!='')
        {
            $query =("SELECT id FROM `categories` WHERE alias = '$cat1' AND `parent_id`='$category'");
            $category1 = $db->fetchOne($query);
                if ($cat2!='')
               {
                   $query =("SELECT id FROM `categories` WHERE alias = '$cat2' AND `parent_id`='$category1'");
                   $category2 = $db->fetchOne($query);
                    if ($cat3!='')
                        {
                            $query =("SELECT id FROM `categories` WHERE alias = '$cat3' AND `parent_id`='$category2'");
                            $category3 = $db->fetchOne($query);
                             return $category3;
                        }
                return $category2;
                }
        return $category1;
        }*/
     //  print_r($category);
        //$cat = new DatabaseObject_Categories($db);
       //$cat->load($alias, 'alias');


       return $category;
    }
    
     public static function GetMetaTag($db, $id) {
        $cat = new DatabaseObject_Categories($db);
        $cat->load($id);
        $temp['title'] = $cat->title;
        $temp['descr'] = $cat->descr;
        $temp['keywords'] = $cat->keywords;
        
        return $temp;
    }
     public static function GetCatsSelect($db, $id) {
        $query = ("SELECT id,name FROM `categories` WHERE parent_id=".$id." ORDER BY name ASC");
        $temp = $db->fetchAll($query);
        return $temp;
    }
    //получение категории для админки
    public static function GetChildAdmin($db, $catId = 0, $lvl = false) {
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, '*');
        $select->where('parent_id  = ?', $catId);
        $data = $db->fetchAll($select);
        if (count($data) == 0 && $catId != 0 && $flag) {
            $cats22 = DatabaseObject_Categories::GetCatsParent($db, $catId);
            return $cats22;
        }

        $cats = self::BuildMultiple($db, __CLASS__, $data);
        //if (!$flag)
            foreach ($cats as $key => $value) {
                //$value->count = DatabaseObject_Products::GetUserProductCount($db, false, $value->getId());
                $value->child = DatabaseObject_Categories::GetChild($db, $value->getId());
                 /* foreach ($value->child as $child) {
                       $child->count = DatabaseObject_Products::GetUserProductCount($db, false, $child->getId());
            }*/
            }
        return $cats;
    }

}

?>
